package com.ronghuanet.user.service.impl;

import com.ronghuanet.basic.util.AjaxResult;
import com.ronghuanet.basic.util.MD5Utils;
import com.ronghuanet.basic.util.StrUtils;
import com.ronghuanet.user.config.RegisterNoticeRabbitmqConfig;
import com.ronghuanet.user.domain.Logininfo;
import com.ronghuanet.user.domain.User;
import com.ronghuanet.user.dto.PhoneRegisterDto;
import com.ronghuanet.user.dto.RegisterNoticeDto;
import com.ronghuanet.user.mapper.LogininfoMapper;
import com.ronghuanet.user.mapper.UserMapper;
import com.ronghuanet.user.service.IUserService;
import com.ronghuanet.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2022-09-15
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    public AjaxResult registerPhone(PhoneRegisterDto phoneRegisterDto) {
        String mobile = phoneRegisterDto.getMobile();
        String username = phoneRegisterDto.getUsername();
        String password = phoneRegisterDto.getPassword();
        String confirmPassword = phoneRegisterDto.getConfirmPassword();
        String smsCode = phoneRegisterDto.getSmsCode();
        //1 校验
        //1.1 null检验
        //1.2 密码与确认密码校验
        if (!password.trim().equals(confirmPassword.trim()))
            return AjaxResult.me().setSuccess(false).setMessage("两次密码不一致！");
        //1.3 短信验证码
        String key ="register_sms_code_" + mobile;

        String smsCodeOfRedis = (String) redisTemplate.opsForValue() //code:time
                .get(key);
        if (StringUtils.isEmpty(smsCodeOfRedis)||
                !smsCodeOfRedis.split(":")[0].equals(smsCode))
            return AjaxResult.me().setSuccess(false).setMessage("短信验证码过期或者错误！");

        //1.4 用户是否存在（用户名）
        User userByDb = userMapper.loadByUsername(username);
        if (userByDb!=null)
            return AjaxResult.me().setSuccess(false).setMessage("该用户名对应的用户已经存在，不能注册！");

        //2 保存登录信息
        Logininfo logininfo = new Logininfo();
        logininfo.setUsername(username);
        logininfo.setPhone(mobile);
        String salt = StrUtils.getComplexRandomString(32);
        salt = "yaosang" + salt + "jfjfjfjfj";
        String securityPwd = MD5Utils.encrypByMd5(password + salt);
        logininfo.setSalt(salt);
        logininfo.setPassword(securityPwd);

        logininfo.setType(Logininfo.LOGININFO_TYPE_USER);
        logininfo.setDisable(1);
        logininfoMapper.save(logininfo);

        //3 保存用户信息
        User user = new User();
        BeanUtils.copyProperties(logininfo,user);
        user.setId(null);
        user.setCreatetime(new Date());
        user.setLogininfoId(logininfo.getId());
        /**
         * 已注册0 已激活2 禁用-1
         */
        user.setState(2);
        userMapper.save(user);

        //4 发通知-短信，邮件通知
        rabbitTemplate.convertAndSend(RegisterNoticeRabbitmqConfig.EXCHANGE_TOPICS_INFORM,
                "inform.sms",
                new RegisterNoticeDto(mobile,"收到短信通知：你好！你注册的账号已经完成，可以正常使用了！"));  //收件人（phone） 消息内容
        rabbitTemplate.convertAndSend(RegisterNoticeRabbitmqConfig.EXCHANGE_TOPICS_INFORM,
                "inform.email",
                new RegisterNoticeDto(mobile,"收到邮件通知：你好！你注册的账号已经完成，可以正常使用了！"));  //收件人（email） 消息内容
        return AjaxResult.me();
    }
}
